package com.jprocms.module.cms.controller.directive;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.jpro.framework.common.util.collection.CollectionUtils;
import com.jprocms.module.cms.controller.admin.imgblock.vo.ImgblockPageReqVO;
import com.jprocms.module.cms.dal.dataobject.channel.ChannelDO;
import com.jprocms.module.cms.dal.dataobject.imgblock.ImgblockDO;
import com.jprocms.module.cms.enums.EnumCommonStatus;
import com.jprocms.module.cms.enums.EnumIntCommonStatus;
import com.jprocms.module.cms.service.channel.ChannelService;
import com.jprocms.module.cms.service.imgblock.ImgblockService;
import com.jprocms.module.cms.util.Freemarkers;
import com.jprocms.module.cms.util.FrontContextUtil;
import com.jprocms.module.cms.web.Directives;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static com.jprocms.module.cms.controller.directive.TagListDirective.SITE_ID;

/**
 * 飘窗 自定义标签
 * 优先 取id
 * 其次根据code查询符合的板块，需要开启并且时间范围是在有效期内的的第一个
 *
 * @author jprocms
 */
public class ImgblockDirective implements TemplateDirectiveModel {
    /**
     * 板块标识
     */
    private static final String CODE = "code";
    /**
     * 飘窗id
     */
    private static final String ID = "id";

    @SuppressWarnings("unchecked")
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        Freemarkers.requireLoopVars(loopVars);
        Freemarkers.requireBody(body);
        Long id = Directives.getLong(params, ID);
        ImgblockDO imgblockDO = new ImgblockDO();
        List<ImgblockDO> imgblockDOS = new ArrayList<>();
        if (id != null) {
            imgblockDO = imgblockService.getImgblock(id);
            imgblockDOS.add(imgblockDO);
        } else {
            String code = Directives.getString(params, CODE);
            if (StringUtils.isBlank(code)) {
                throw new IllegalArgumentException("Params id or code is required.");
            }
            Long defSiteId = FrontContextUtil.getSiteId(env);
            Long siteId = Directives.getLong(params, SITE_ID, defSiteId);
            ImgblockPageReqVO reqVO = new ImgblockPageReqVO();
            reqVO.setSiteId(siteId);
            reqVO.setImgblockCode(code);
            imgblockDOS.addAll(imgblockService.getImgblockList(reqVO));
        }
        final LocalDateTime now = LocalDateTime.now();
        Predicate<ImgblockDO> enableCondition = p -> EnumCommonStatus.OPEN.getStatus().equals(p.getStatus());
        Predicate<ImgblockDO> beginCondition = p -> p.getActivetimeBegin()==null||p.getActivetimeBegin().isBefore(now) ;
        Predicate<ImgblockDO> endCondition = p -> p.getActivetimeEnd()==null||p.getActivetimeEnd().isAfter(now);
        Predicate<ImgblockDO> finalCondition =  enableCondition.and(beginCondition.and(endCondition));
        final List<ImgblockDO> filterImgBlocks = imgblockDOS.stream().filter(finalCondition).collect(Collectors.toList());
        //存在多个的情况下按开始时间排序 取第一个
        final List<ImgblockDO> sortImgBlocks = CollUtil.sort(filterImgBlocks, Comparator.comparing(ImgblockDO::getActivetimeBegin));
        if(CollUtil.isNotEmpty(sortImgBlocks)){
            imgblockDO = sortImgBlocks.get(0);
        }
        //查询下是为了直接关联查询出图片
        loopVars[0] = env.getObjectWrapper().wrap(imgblockService.getImgblock(imgblockDO.getId()));
        body.render(env.getOut());
    }

    private final ImgblockService imgblockService;

    public ImgblockDirective(ImgblockService imgblockService) {
        this.imgblockService = imgblockService;
    }
}
